package club.janna.concurrency.example.singleton;

import club.janna.concurrency.annotation.ThreadUnSafe;

/**
 * 单例模式-懒汉模式
 * 第一次使用时进行初始化
 * @Auther: guopanbo
 * @Date: 2018/8/1 21:49
 * @Description:
 */
@ThreadUnSafe
public class SingletonExample4 {

    private SingletonExample4() {}

    private static SingletonExample4 instance = null;


    /**
     * 将synchronized块缩小，但由于JVM和cpu的优化，new Singleton()的指令进行重排序，会导致结果和预期不一致，所以，线程不安全
     * @return
     */
    public static SingletonExample4 getInstance() {
        if(instance == null) {
            synchronized (SingletonExample4.class) {
                if(instance == null)
                    instance = new SingletonExample4();
            }
        }
        return instance;
    }
}
